from django.db import models
from django.conf import settings
import django.utils.timezone
from user.models import SysUser  # 导入自定义用户模型

class ResumeChatSession(models.Model):
    """简历助手对话会话模型 - 管理一组相关对话"""
    user = models.ForeignKey(
        SysUser,  # 关联自定义用户表
        on_delete=models.CASCADE,
        related_name='resume_chat_sessions',
        verbose_name='用户'
    )

    title = models.CharField(
        max_length=200,
        help_text='会话标题（通常用首条消息摘要）'
    )
    resume_filename = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        help_text='关联的简历文件名'
    )
    resume_text = models.TextField(
        blank=True,
        null=True,
        help_text='简历文本内容'
    )
    created_at = models.DateTimeField(
        default=django.utils.timezone.now,
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    is_archived = models.BooleanField(
        default=False,
        help_text='是否归档'
    )

    class Meta:
        verbose_name = '简历助手会话'
        verbose_name_plural = '简历助手会话'
        ordering = ['-updated_at']

    def __str__(self):
        return f"{self.user.username}的简历会话：{self.title[:20]}"


class ResumeChatMessage(models.Model):
    """简历助手对话消息模型 - 存储单条消息"""
    SENDER_CHOICES = [
        ('user', '用户'),
        ('ai', 'AI')
    ]
    session = models.ForeignKey(
        ResumeChatSession,
        on_delete=models.CASCADE,
        related_name='messages',
        verbose_name='所属会话'
    )
    sender = models.CharField(
        max_length=10,
        choices=SENDER_CHOICES,
        verbose_name='发送者'
    )
    content = models.TextField(
        help_text='消息内容'
    )
    created_at = models.DateTimeField(
        default=django.utils.timezone.now,
        verbose_name='发送时间'
    )
    tokens_used = models.IntegerField(
        default=0,
        help_text='AI消息消耗的token数（用户消息为0）'
    )
    response_time = models.FloatField(
        default=0.0,
        help_text='AI回复耗时（秒）'
    )

    class Meta:
        verbose_name = '简历助手消息'
        verbose_name_plural = '简历助手消息'
        ordering = ['created_at']

    def __str__(self):
        return f"{self.get_sender_display()}：{self.content[:20]}..."